# encoding: utf-8

# sql导出
# mysqldump -u root -p db_name > test_db.sql

import MySQLdb
from widget.db_init.configuration import sql_configuration as LM


class MySqlOp(object):
    def __init__(self, host=None, db_name=None):
        if host and db_name:
            self.host = host
            self.port = LM[host]['port']
            self.user = LM[host]['user']
            self.passwd = LM[host]['passwd']
            self.db_name = db_name
            self.charset = LM[host]['charset']

    def operate(self, sql):
        db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name, charset=self.charset)
        cur = db.cursor()
        try:
            # 执行sql语句
            cur.execute(sql)
            cur.close()
            # 提交到数据库执行
            db.commit()
        except Exception as e:
            print(e)
            cur.close()
            # Rollback in case there is any error
            db.rollback()
        # 关闭数据库连接
        db.close()

    def select(self, sql):
        db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name, charset=self.charset)
        cur = db.cursor()
        results = None
        try:
            # 执行sql语句
            cur.execute(sql)
            # 获取所有记录列表
            results = cur.fetchall()
            # print(results)
        except Exception as e:
            print(e)
            # 关闭数据库连接
        db.close()
        return results